package com.yuanqi.java.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanqi.java.dto.PurchaseOrderDetailDTO;
import com.yuanqi.java.dto.PurchaseOrderDetailQueryDTO;
import com.yuanqi.java.dto.PurchaseOrderDetailVO;
import com.yuanqi.java.entity.PurchaseOrderDetail;
import com.yuanqi.java.entity.PurchaseOrder;
import com.yuanqi.java.mapper.PurchaseOrderDetailMapper;
import com.yuanqi.java.service.IPurchaseOrderDetailService;
import com.yuanqi.java.service.IPurchaseOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 采购订单明细表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-01-27
 */
@Service
public class PurchaseOrderDetailServiceImpl extends ServiceImpl<PurchaseOrderDetailMapper, PurchaseOrderDetail> implements IPurchaseOrderDetailService {

    @Autowired
    private IPurchaseOrderService purchaseOrderService;

    @Override
    public Page<PurchaseOrderDetailVO> pageQuery(Page<PurchaseOrderDetail> page, PurchaseOrderDetailQueryDTO queryDTO) {
        // 这里需要关联查询采购订单和供应商信息
        // 由于是示例，我们简化处理，直接查询明细表
        QueryWrapper<PurchaseOrderDetail> queryWrapper = new QueryWrapper<>();
        
        if (queryDTO != null) {
            if (StringUtils.hasText(queryDTO.getProductName())) {
                queryWrapper.like("product_name", queryDTO.getProductName());
            }
            if (StringUtils.hasText(queryDTO.getSpecification())) {
                queryWrapper.like("specification", queryDTO.getSpecification());
            }
            if (StringUtils.hasText(queryDTO.getUnit())) {
                queryWrapper.eq("unit", queryDTO.getUnit());
            }
        }
        
        queryWrapper.orderByDesc("create_time");
        
        Page<PurchaseOrderDetail> detailPage = this.page(page, queryWrapper);
        
        // 转换为VO
        List<PurchaseOrderDetailVO> voList = detailPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        Page<PurchaseOrderDetailVO> resultPage = new Page<>();
        resultPage.setRecords(voList);
        resultPage.setTotal(detailPage.getTotal());
        resultPage.setCurrent(detailPage.getCurrent());
        resultPage.setSize(detailPage.getSize());
        
        return resultPage;
    }

    @Override
    public List<PurchaseOrderDetail> getDetailsByOrderId(Long orderId) {
        QueryWrapper<PurchaseOrderDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        queryWrapper.orderByAsc("id");
        return this.list(queryWrapper);
    }

    @Override
    public boolean saveBatchDetails(List<PurchaseOrderDetailDTO> details) {
        List<PurchaseOrderDetail> entities = details.stream()
                .map(this::convertToEntity)
                .collect(Collectors.toList());
        
        // 计算总价
        entities.forEach(detail -> {
            if (detail.getQuantity() != null && detail.getUnitPrice() != null) {
                detail.setTotalPrice(detail.getUnitPrice().multiply(new BigDecimal(detail.getQuantity())));
            }
        });
        
        return this.saveBatch(entities);
    }

    @Override
    public boolean deleteByOrderId(Long orderId) {
        QueryWrapper<PurchaseOrderDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        return this.remove(queryWrapper);
    }

    /**
     * 转换为VO
     */
    private PurchaseOrderDetailVO convertToVO(PurchaseOrderDetail detail) {
        PurchaseOrderDetailVO vo = new PurchaseOrderDetailVO();
        BeanUtils.copyProperties(detail, vo);
        
        // 关联查询采购订单信息，获取采购单号
        if (detail.getOrderId() != null) {
            PurchaseOrder order = purchaseOrderService.getById(detail.getOrderId());
            if (order != null) {
                vo.setOrderNo(order.getOrderNo());
            }
        }
        
        return vo;
    }

    /**
     * 转换为实体
     */
    private PurchaseOrderDetail convertToEntity(PurchaseOrderDetailDTO dto) {
        PurchaseOrderDetail entity = new PurchaseOrderDetail();
        BeanUtils.copyProperties(dto, entity);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        return entity;
    }
} 